/*
    This file is part of Raptor.

    Raptor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Raptor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Raptor.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <QtCore>
#include <QtGui>
#include <QNetworkProxy>

#include "configDialog.h"
#include "raptor.h"

configDialog::configDialog(QPointer<Raptor> r)
{
	raptor = r;

	contentsWidget = new QListWidget;
	contentsWidget->setViewMode(QListView::IconMode);
	contentsWidget->setIconSize(QSize(96, 84));
	contentsWidget->setMovement(QListView::Static);
	contentsWidget->setMaximumWidth(128);
	contentsWidget->setMinimumHeight(350);
	contentsWidget->setMinimumWidth(128);
	contentsWidget->setSpacing(12);

	pageSettings = new settingsPage(raptor);
	pageHoster = new hosterPage(raptor);

	pagesWidget = new QStackedWidget;
	pagesWidget->addWidget(pageSettings);
	pagesWidget->addWidget(pageHoster);

	//QPointer<QPushButton> acceptButton = new QPushButton(tr("OK"));
	//QPointer<QPushButton> rejectButton = new QPushButton(tr("Cancel"));
	QPointer<QPushButton> finishButton = new QPushButton(tr("Finish"));

	createIcons();
	contentsWidget->setCurrentRow(0);

	connect(finishButton, SIGNAL(clicked()), this, SLOT(slot_finishButton_accept()));

	QPointer<QHBoxLayout> horizontalLayout = new QHBoxLayout;
	horizontalLayout->addWidget(contentsWidget);
	horizontalLayout->addWidget(pagesWidget, 1);

	QPointer<QHBoxLayout> buttonsLayout = new QHBoxLayout;
	buttonsLayout->addStretch(1);
	buttonsLayout->addWidget(finishButton);

	QPointer<QVBoxLayout> mainLayout = new QVBoxLayout;
	mainLayout->addLayout(horizontalLayout);
	//mainLayout->addStretch(1);
	mainLayout->addSpacing(12);
	mainLayout->addLayout(buttonsLayout);
	setLayout(mainLayout);

	setWindowTitle(tr("Settings"));
}

void configDialog::slot_finishButton_accept()
{
	accept();
}

void configDialog::createIcons()
{
	QListWidgetItem * configButton = new QListWidgetItem(contentsWidget);
	configButton->setIcon(QIcon(":/toolbar/raptor_v2.svg"));
	configButton->setText(tr("Settings"));
	configButton->setTextAlignment(Qt::AlignHCenter);
	configButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);

	QListWidgetItem *hosterButton = new QListWidgetItem(contentsWidget);
	hosterButton->setIcon(QIcon(":/toolbar/container.svg"));
	hosterButton->setText(tr("Hoster"));
	hosterButton->setTextAlignment(Qt::AlignHCenter);
	hosterButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);

	connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem*)));
}

void configDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous)
{
	if(!current) current = previous;

	pagesWidget->setCurrentIndex(contentsWidget->row(current));
}

settingsPage::settingsPage(QPointer<Raptor> r)
{
	raptor = r;

	configGroup = new QGroupBox(tr("Raptor configuration"));

        raptorFolderLabel = new QLabel(tr("Raptor folder:"));
        raptorFolderButton = new QPushButton(tr("Select Folder"));
        raptorFolder = new QLineEdit("");

        downloadFolderLabel = new QLabel(tr("Download folder:"));
        downloadFolderButton = new QPushButton(tr("Select Folder"));
        downloadFolder = new QLineEdit("");

	proxyLabel1 = new QLabel(tr("Proxy settings:"));
	proxyLabel2 = new QLabel(tr("Authentication required (User, Pass):"));
	proxyHost = new QLineEdit("");
	proxyUser = new QLineEdit("");
	proxyPass = new QLineEdit("");
	proxyPort = new QSpinBox();
	proxyType = new QComboBox();

	proxyType->addItem("NoProxy", QNetworkProxy::NoProxy);
	proxyType->addItem("Socks5Proxy", QNetworkProxy::Socks5Proxy);
	proxyType->addItem("HttpProxy", QNetworkProxy::HttpProxy);

	sslCheckBox = new QCheckBox(tr("Use SSL"));

	maxDownloadsLabel = new QLabel(tr("Maximum simultaneous downloads:"));
	maxDownloadsSpinBox = new QSpinBox();

	applyButton = new QPushButton("Apply");

	groupLayout = new QGridLayout;
        groupLayout->addWidget(raptorFolderLabel, 0, 0);
        groupLayout->addWidget(raptorFolder, 0, 1, 1, 2);
        groupLayout->addWidget(raptorFolderButton, 0, 3);

        groupLayout->addWidget(downloadFolderLabel, 1, 0);
        groupLayout->addWidget(downloadFolder, 1, 1, 1, 2);
        groupLayout->addWidget(downloadFolderButton, 1, 3);

        groupLayout->addWidget(proxyLabel1, 2, 0);
        groupLayout->addWidget(proxyHost, 2, 1);
        groupLayout->addWidget(proxyPort, 2, 2);
        groupLayout->addWidget(proxyType, 2, 3);

        groupLayout->addWidget(proxyLabel2, 3, 0, 1, 2, Qt::AlignRight);
        groupLayout->addWidget(proxyUser, 3, 2);
        groupLayout->addWidget(proxyPass, 3, 3);

	groupLayout->addWidget(sslCheckBox, 4, 0);

	groupLayout->addWidget(maxDownloadsLabel, 5, 0);
	groupLayout->addWidget(maxDownloadsSpinBox, 5, 1);

	configGroup->setLayout(groupLayout);

	mainLayout = new QGridLayout;
	mainLayout->addWidget(configGroup, 0, 0);
	mainLayout->addWidget(applyButton, 1, 0, Qt::AlignRight);

	setLayout(mainLayout);

	connect(applyButton, SIGNAL(clicked()), this, SLOT(slot_applyButton_clicked()));

        connect(raptorFolderButton, SIGNAL(clicked()), this, SLOT(slot_raptorFolderButton_clicked()));
        connect(downloadFolderButton, SIGNAL(clicked()), this, SLOT(slot_downloadFolderButton_clicked()));

        raptorFolder->setText(raptor->folders.raptor.absolutePath());
        downloadFolder->setText(raptor->folders.download.absolutePath());

	maxDownloadsSpinBox->setValue(raptor->maxDownloads);

        proxyHost->setText(raptor->proxy.host);
	proxyPort->setRange(0, 65536);
	proxyPort->setValue(raptor->proxy.port);

	int tmpInt = proxyType->findData(raptor->proxy.type);
	if(tmpInt >= 0)
		proxyType->setCurrentIndex(tmpInt);
	else
		proxyType->setCurrentIndex(0);

	proxyUser->setText(raptor->proxy.user);
	proxyPass->setText(raptor->proxy.pass);
	proxyPass->setEchoMode(QLineEdit::Password);

	sslCheckBox->setChecked(raptor->useSSL);
}

settingsPage::~settingsPage()
{
    if(configGroup) delete configGroup;

    if(downloadFolderLabel) delete downloadFolderLabel;
    if(downloadFolderButton) delete downloadFolderButton;
    if(downloadFolder) delete downloadFolder;

    if(raptorFolderLabel) delete raptorFolderLabel;
    if(raptorFolderButton) delete raptorFolderButton;
    if(raptorFolder) delete raptorFolder;

    if(proxyLabel1) delete proxyLabel1;
    if(proxyLabel2) delete proxyLabel2;
    if(proxyHost) delete proxyHost;
    if(proxyPort) delete proxyPort;
    if(proxyType) delete proxyType;
    if(proxyUser) delete proxyUser;
    if(proxyPass) delete proxyPass;

    if(sslCheckBox) delete sslCheckBox;

    if(maxDownloadsLabel) delete maxDownloadsLabel;
    if(maxDownloadsSpinBox) delete maxDownloadsSpinBox;

    if(applyButton) delete applyButton;

    if(groupLayout) delete groupLayout;
    if(mainLayout) delete mainLayout;
}

void settingsPage::slot_applyButton_clicked()
{
    QSettings settings("raptor-loader", "Raptor");

    settings.setValue("folderRaptor", raptorFolder->text());
    settings.setValue("folderDownload", downloadFolder->text());

    settings.setValue("maxDownloads", maxDownloadsSpinBox->value());

    settings.setValue("proxy/host", proxyHost->text());
    settings.setValue("proxy/port", proxyPort->value());
    settings.setValue("proxy/type", proxyType->itemData(proxyType->currentIndex()));
    settings.setValue("proxy/user", proxyUser->text());
    settings.setValue("proxy/pass", proxyPass->text());

    settings.setValue("useSSL", sslCheckBox->isChecked());
}

void settingsPage::slot_raptorFolderButton_clicked()
{
    QString fileName = QFileDialog::getExistingDirectory(this, tr("Open Directory"), raptorFolder->text(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if(!fileName.isEmpty()) raptorFolder->setText(fileName);
}

void settingsPage::slot_downloadFolderButton_clicked()
{
    QString fileName = QFileDialog::getExistingDirectory(this, tr("Open Directory"), downloadFolder->text(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if(!fileName.isEmpty()) downloadFolder->setText(fileName);
}

hosterPage::hosterPage(QPointer<Raptor> r)
{
	raptor = r;

	mainLayout = new QGridLayout;
	groupLayout = new QGridLayout;

	applyButton = new QPushButton("Apply");

	configGroup = new QGroupBox(tr("Hoster configuration"));
	hosterLabel = new QLabel(tr("Select Hoster:"));
	hosterCombo = new QComboBox;

	authLabel = new QLabel(tr("Premium Account Login:"));
	authUser = new QLineEdit("");
	authPass = new QLineEdit("");
	authPass->setEchoMode(QLineEdit::Password);
	authLogin = new QPushButton(tr("Login and save Cookie"));
	authDelete = new QPushButton(tr("Delete Cookie"));

	maxDownloadsLabel = new QLabel(tr("Maximum simultaneous downloads:"));
	maxDownloadsSpinBox = new QSpinBox();

	connect(hosterCombo, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(slot_hosterCombo_currentIndexChanged(const QString &)));
	connect(authLogin, SIGNAL(clicked()), this, SLOT(slot_authLoginButton_clicked()));
	connect(authDelete, SIGNAL(clicked()), this, SLOT(slot_authDeleteButton_clicked()));
	connect(applyButton, SIGNAL(clicked()), this, SLOT(slot_applyButton_clicked()));

	groupLayout->addWidget(hosterLabel, 0, 0);
	groupLayout->addWidget(hosterCombo, 0, 1);

	groupLayout->addWidget(authLabel, 1, 0);
	groupLayout->addWidget(authUser, 1, 1);
	groupLayout->addWidget(authPass, 1, 2);
	groupLayout->addWidget(authLogin, 1, 3);
	groupLayout->addWidget(authDelete, 1, 4);

	groupLayout->addWidget(maxDownloadsLabel, 2, 0);
	groupLayout->addWidget(maxDownloadsSpinBox, 2, 1);

	configGroup->setLayout(groupLayout);

	mainLayout = new QGridLayout;
	mainLayout->addWidget(configGroup, 0, 0);
	mainLayout->addWidget(applyButton, 1, 0, Qt::AlignRight);

	setLayout(mainLayout);

	for(int i=0; i<raptor->hosterList.size(); ++i)
	{
        hosterCombo->addItem(raptor->hosterList.at(i)->info().host);
	}

	if(raptor->hosterList.size() > 0) loadHosterSettings(0);
}

hosterPage::~hosterPage()
{
	if(applyButton) delete applyButton;

	if(configGroup) delete configGroup;
	if(hosterLabel) delete hosterLabel;
	if(hosterCombo) delete hosterCombo;
	if(authDelete) delete authDelete;

	if(groupLayout) delete groupLayout;
	if(mainLayout) delete mainLayout;
}

void hosterPage::slot_hosterCombo_currentIndexChanged(const QString &text)
{
	int hosterId = 0;

	for(int i=0; i<raptor->hosterList.size(); ++i)
	{
        if(text == raptor->hosterList.at(i)->info().host)
		{
			hosterId = i;
			break;
		}
	}

	loadHosterSettings(hosterId);
}

void hosterPage::loadHosterSettings(const int &hoster)
{
	if(hoster < 0 || hoster >= raptor->hosterList.size()) return;

    maxDownloadsSpinBox->setValue(raptor->hosterList.at(hoster)->info().maxDownloads);
}

void hosterPage::slot_applyButton_clicked()
{
	QSettings settings("raptor-loader", "Raptor");

	settings.setValue("hoster/" + hosterCombo->currentText() + "/maxDownloads", maxDownloadsSpinBox->value());

    raptor->setMaxDownloads(hosterCombo->currentText(), maxDownloadsSpinBox->value());
}

void hosterPage::slot_authLoginButton_clicked()
{
	connect(raptor, SIGNAL(hosterLoginFinished(const bool)), this, SLOT(slot_raptor_hosterLoginFinished(const bool)));

	raptor->doHosterLogin(hosterCombo->currentText(), authUser->text(), authPass->text());
}

void hosterPage::slot_authDeleteButton_clicked()
{
	QSettings settings("raptor-loader", "Raptor");

	settings.beginGroup("hoster/" + hosterCombo->currentText() + "/settings");
	settings.remove("");
	settings.endGroup();

    raptor->setModeFree(hosterCombo->currentText());
}

void hosterPage::slot_raptor_hosterLoginFinished(const bool error)
{
	disconnect(raptor, SIGNAL(hosterLoginFinished(const bool)), this, SLOT(slot_raptor_hosterLoginFinished(const bool)));

	if(error)
	{
		QMessageBox::information(this, "Login", "Login failed.");

		slot_authDeleteButton_clicked();
	} else
	{
		QMessageBox::information(this, "Login", "Login was successful.");
	}
}
